import json
from datetime import datetime

from flask import g, request

from application import db
from web.models.AppAccessLog import AppAccessLog
from web.models.AppErrorLog import AppErrorLog


class LogService(object):
    @staticmethod
    def addAccesslog():
        """添加访问日志到数据库"""
        target = AppAccessLog()
        if "current_user" in g and g.current_user is not None:
            target.uid = g.current_user.uid  # 当前用户的yid
        target.referer_url = request.referrer
        target.target_url = request.url
        target.query_params = json.dumps(request.values.to_dict())
        target.ua = request.headers.get("User-Agent")
        target.created_time = datetime.now()
        # 写入数据库
        db.session.add(target)
        db.session.commit()
        return True

    @staticmethod
    def addErrorlog(content):
        """添加错误日志到数据库"""
        if "favicon.ico" in request.url:
            print("图标问题报404可以忽略")
            return
        target = AppErrorLog()
        target.referer_url = request.referrer
        target.target_url = request.url
        target.query_params = json.dumps(request.values.to_dict())
        target.content = content
        target.created_time = datetime.now()
        # 写入数据库
        db.session.add(target)
        db.session.commit()
        print("写入数据库成功")
        return True